package org.numb.concurrency.chapter03;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        // semaphore模拟保证最多并发运行5个线程
        for (int i = 0; i < 10; i++) {
            final int num = i;
            Thread thread = new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("线程池仍有空闲，线程" + num + "提交成功");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println("线程" + num + "结束");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }
    }

}
